<template>
  <div>
    <el-container>
      <el-aside class="aside">
        <el-form :model="post">
          <el-form-item label="标题">
            <el-input v-model="post.title" />
          </el-form-item>
          <el-form-item label="分类">
            <el-input v-model="post.sort" />
          </el-form-item>
          <el-form-item label="封面">
            <img :src="post.image"
              style="width: 120px; box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 2px 6px 2px;" />
            <el-button v-show="!upload" style="margin-left: 1px;">
              <el-upload accept="image/jpeg,image/gif,image/png" :file-list="files" :auto-upload='false'
                :show-file-list="false" :on-change="onChange">
                选择图片
              </el-upload>
            </el-button>
            <el-button style="margin-left: 1px;" @click="handleUploadOneImage" v-show="upload">上传头像
            </el-button>
          </el-form-item>
          <el-form-item style="display: flex; justify-content: space-between">
            <el-button type="primary" @click="postSubmit">提交</el-button>
            <el-button style="margin-left: 100px">取消</el-button>
          </el-form-item>
        </el-form>
      </el-aside>

      <el-main>
        <v-md-editor v-model="post.detail" :disabled-menus="[]" @upload-image="handleUploadImage" left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image align| customToolbar1 
                    customToolbar2 customToolbar3 |code save" :toolbar="toolbar" height="100vh">
        </v-md-editor>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
  import request from "@/utils/request";
  import { ElMessage } from "element-plus";
  import { useRoute } from "vue-router";

  let route = useRoute();
  const postId = route.query.postId;
  const post = ref({});
  const files = ref([]);
  const upload = ref(false);

  onBeforeMount(() => {
    if (postId === "") {
      post.value = {
        role: JSON.parse(localStorage.getItem("user")).role,
        userId: JSON.parse(localStorage.getItem("user")).userId,
        title: "",
        sort: "",
        image: "",
        detail: "",
      };
    } else {
      request.get(`/post/getOne/${postId}`).then((res) => {
        post.value = res.data;
      });
    }
  });

  const handleUploadImage = (event, insertImage, files) => {
    for (let i in files) {
      const formData = new FormData();
      formData.append("file", files[i]);
      request.post(`/uploadImg`, formData).then((res) => {
        insertImage({
          url: res.data,
          desc: "描述",
        });
      });
    }
  };

  const postSubmit = () => {
    console.log(postId);
    if (postId === "") {
      request.post(`/post/insertOne`, post.value).then((res) => {
        if (res.code == -1) {
          ElMessage.warning(res.msg);
        } else {
          ElMessage.success("增加帖子成功");
        }
      });
    } else {
      request.post(`/post/updateOne`, post.value).then((res) => {
        if (res.code == -1) {
          ElMessage.warning(res.msg);
        } else {
          ElMessage.success("更新帖子成功");
        }
      });
    }
  };

  const onChange = (file, fileList) => {
    files.value.push(file.raw);
    upload.value = true;
  };

  const handleUploadOneImage = () => {
    const formData = new FormData();
    formData.append('file', files.value[0]);
    request.post(`/uploadImg`, formData).then((res) => {
      post.value.image = res.data;
      upload.value = false;
      files.value = [];
    });
  };

  const toolbar = ref({
    customToolbar1: {
      title: "设置图片大小",
      icon: "v-md-icon-tip",
      action(editor) {
        editor.insert(function (selected) {
          const prefix = "{{{";
          const suffix = "}}}";
          const placeholder = 'width="100" height="auto"';
          const content = selected || placeholder;

          return {
            text: `${prefix}${content}${suffix}`,
            selected: content,
          };
        });
      },
    },
    customToolbar2: {
      title: "全角空格",
      icon: "v-md-icon-tip",
      action(editor) {
        editor.insert(function (selected) {
          const prefix = "";
          const suffix = "";
          const placeholder = "&emsp;";
          const content = selected || placeholder;

          return {
            text: `${prefix}${content}${suffix}`,
            selected: content,
          };
        });
      },
    },
    customToolbar3: {
      title: "半角空格",
      icon: "v-md-icon-tip",
      action(editor) {
        editor.insert(function (selected) {
          const prefix = "";
          const suffix = "";
          const placeholder = "&ensp;";
          const content = selected || placeholder;

          return {
            text: `${prefix}${content}${suffix}`,
            selected: content,
          };
        });
      },
    }
  });
</script>

<style lang="less" scoped>
  .aside {
    width: 300px;
    height: 100vh;
    padding: 25px;
  }
</style>